<?php

namespace Mouta\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Mouta\UserBundle\Form\Type\ImageType;
use Mouta\AmistateBundle\Entity\Image;
use Symfony\Component\HttpFoundation\Response;

class FotosController extends Controller
{
    public function indexAction()
    {
        $user = $this->getUser();
        $images = $user->getImages();
        
        $imageForm = $this->createForm(new ImageType(), new Image());
        
        $request = $this->getRequest();
        if ($request->isMethod('POST')) 
        {
            
            $imageForm->bind($request);
            if ($imageForm->isValid()) 
			{
                $em = $this->getDoctrine()->getManager();
                $image = $imageForm->getData();
                $image->setUsuario($user);
                $em->persist($image);
                $em->flush();
            } else {
                $this->get('session')->getFlashBag()->add(
                    'error-'.$imageForm->getConfig()->getName(),
                    'No pudimos subir la imagen, prueba con otra'
                );
            }
            
            return $this->redirect($this->generateUrl('user_perfil').'#fotos');
        }
        
        return $this->render('UserBundle:Fotos:index.html.twig',array(
            'user'=>$user,
            'images'=>$images,
            'form' => $imageForm->createView(),
        ));
    }
	
	private function getImageSubmit()
	{
		$user = $this->getUser();
		$request = $this->getRequest();
        if ($request->isMethod('POST')) 
        {
			$em = $this->getDoctrine()->getManager();
			$imagen = $em->getRepository('AmistateBundle:Image')->find($request->get("id"));
			if($imagen && $imagen->getUsuario()->getId() == $user->getId())
			{
				return $imagen;
			}
		}
		return null;
	}
    
    public function saveAction()
    {
		$imagen = $this->getImageSubmit();
		$user = $this->getUser();
        if($imagen)
		{
			$request = $this->getRequest();
			$em = $this->getDoctrine()->getManager();
			
			$nombre = $request->get('nombre');
			
			if($nombre)
			{
				$imagen->setNombre($nombre);
			}
			
			$default = $request->get('default');
			if($default)
			{
				$imagenes = $em->getRepository('AmistateBundle:Image')->findBy(array('usuario'=>$user->getId()));
				foreach($imagenes as $img)
				{
					if($img->getPrincipal())
					{
						$img->setPrincipal(false);
						$em->persist($img);
					}
				}
				$imagen->setPrincipal(true);
			}
			
			$em->persist($imagen);
			$em->flush();
		}
		return new Response(json_encode( array('success'=>true) ));
    }
	
	public function deleteAction()
	{
		$imagen = $this->getImageSubmit();
        if($imagen)
		{
			$em = $this->getDoctrine()->getManager();
			$em->remove($imagen);
			$em->flush();
		}
		return new Response(json_encode( array('success'=>true) ));
	}

}
